#include <stdio.h>

#include "XmlUtils.hpp"

bool XmlUtils::WriteTextToFile(const char* pFile, const char* pText)
{
	FILE* fp = fopen(pFile, "wt");
	fputs(pText, fp);
	fclose(fp);
	return true;
}

TiXmlElement* XmlUtils::GetElement(TiXmlElement* pElement, const char* name)
{
	return pElement?pElement->FirstChildElement(name):NULL;
}

const char* XmlUtils::GetText(TiXmlElement* pElement)
{
	return pElement?pElement->GetText():NULL;
}

const char* XmlUtils::GetText(TiXmlElement* pElement, const char* name)
{
	return pElement?GetText(pElement->FirstChildElement(name)):NULL;
}

bool XmlUtils::GetValue(TiXmlElement* pElement, char* value, size_t len)
{
	const char* pText = GetText(pElement);
	if(!pText) return false;
	size_t tlen = strlen(pText);
	if(tlen>=len) return false;
	memcpy(value, pText, tlen+1);
	return true;
}

bool XmlUtils::GetValue(TiXmlElement* pElement, bool& value)
{
	const char* pText = GetText(pElement);
	if(!pText) return false;
	if(strcmp(pText, "true")==0)	{ value = true;	return true; }
	if(strcmp(pText, "false")==0)	{ value = false;return true; } 
	value = (atoi(pText)!=0);
	return true;
}

bool XmlUtils::GetValue(TiXmlElement* pElement, const char* name, char* value, size_t len)
{
	const char* pText = GetText(pElement, name);
	if(!pText) return false;
	size_t tlen = strlen(pText);
	if(tlen>=len) return false;
	memcpy(value, pText, tlen+1);
	return true;
}

bool XmlUtils::GetValue(TiXmlElement* pElement, const char* name, bool& value)
{
	const char* pText = GetText(pElement, name);
	if(!pText) return false;
	if(strcmp(pText, "true")==0)	{ value = true;	return true; }
	if(strcmp(pText, "false")==0)	{ value = false;return true; } 
	value = (atoi(pText)!=0);
	return true;
}

const char* XmlUtils::GetAttribute(TiXmlElement* pElement, const char* name)
{
	return pElement?pElement->Attribute(name):NULL;
}

bool XmlUtils::GetAttribute(TiXmlElement* pElement, const char* name, char* value, size_t len)
{
	const char* pText = GetAttribute(pElement, name);
	if(!pText) return false;
	size_t tlen = strlen(pText);
	if(tlen>=len) return false;
	memcpy(value, pText, tlen+1);
	return true;
}

bool XmlUtils::GetAttribute(TiXmlElement* pElement, const char* name, bool& value)
{
	const char* pText = GetAttribute(pElement, name);
	if(!pText) return false;
	if(strcmp(pText, "true")==0)	{ value = true;	return true; }
	if(strcmp(pText, "false")==0)	{ value = false;return true; } 
	value = (atoi(pText)!=0);
	return true;
}
